package com.lc.zpyh.ui.fragment.order;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.util.Log;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.hjq.http.EasyHttp;
import com.hjq.http.lifecycle.ApplicationLifecycle;
import com.hjq.http.listener.HttpCallback;
import com.hjq.http.listener.OnHttpListener;
import com.lc.base.BaseDialog;
import com.lc.zpyh.R;
import com.lc.zpyh.adapter.CountDownAdapter;
import com.lc.zpyh.app.AppFragment;
import com.lc.zpyh.http.DeleteOrderApi;
import com.lc.zpyh.http.glide.GlideApp;
import com.lc.zpyh.http.request.BuyAgainApi;
import com.lc.zpyh.http.request.CancelOrdereApi;
import com.lc.zpyh.http.request.ConfirmReceiptApi;
import com.lc.zpyh.http.request.OrderApi;
import com.lc.zpyh.http.request.PublicMsgBean;
import com.lc.zpyh.http.request.RefundOrderApi;
import com.lc.zpyh.http.request.ReimburseApi;
import com.lc.zpyh.http.request.ReimburseBean;
import com.lc.zpyh.http.response.BuyAgainBean;
import com.lc.zpyh.http.response.ConfirmReceiptBean;
import com.lc.zpyh.http.response.OrderBean;
import com.lc.zpyh.http.response.RefundOrderBean;
import com.lc.zpyh.other.IntentKey;
import com.lc.zpyh.ui.activity.order.OrderDetailsActivity;
import com.lc.zpyh.ui.activity.order.OrderServedDetailsActivty;
import com.lc.zpyh.ui.activity.order.ShopCommentActivity;
import com.lc.zpyh.ui.activity.supermarket.BusinessActivity;
import com.lc.zpyh.ui.activity.supermarket.PayActivity;
import com.lc.zpyh.ui.dialog.MessageDialog;
import com.lc.zpyh.util.BigDecimalUtils;
import com.lc.zpyh.util.MyDecoration;
import com.lc.zpyh.util.SPUtil;
import com.lc.zpyh.util.constant.EvenConstant;
import com.lc.zpyh.util.eventbus.Event;
import com.lc.zpyh.util.eventbus.EventBusUtils;
import com.lc.zpyh.view.NpaLinearLayoutManager;
import com.lc.zpyh.view.ShopPhomeDialog;
import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;
import com.yanzhenjie.recyclerview.OnItemMenuClickListener;
import com.yanzhenjie.recyclerview.SwipeMenu;
import com.yanzhenjie.recyclerview.SwipeMenuBridge;
import com.yanzhenjie.recyclerview.SwipeMenuCreator;
import com.yanzhenjie.recyclerview.SwipeMenuItem;
import com.yanzhenjie.recyclerview.SwipeRecyclerView;

import org.jetbrains.annotations.NotNull;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;

public class OrderListFragment extends AppFragment {
    private static final String TAG = "OrderListFragment";
    private static final String ARG_PARAM1 = "param1";
    @BindView(R.id.rv_shop_order)
    SwipeRecyclerView rvShopOrder;
    @BindView(R.id.layout_refresh)
    TwinklingRefreshLayout refreshLayout;
    private String system_id="";
    private int page=1;

    private BaseQuickAdapter<OrderBean.ListDTO, CountDownAdapter.MyViewHolder> adapter;
    private BaseQuickAdapter<OrderBean.DetailsDTO, BaseViewHolder> goodsAdp;
    private List<OrderBean.ListDTO> dtsu=new ArrayList<>();
    //记录每次刷新时的时间
    private long tempTime;
//    装计时器的集合
    private SparseArray<CountDownTimer> timerArray = new SparseArray<>();
    public static OrderListFragment newInstance(String system_id) {
        OrderListFragment fragment = new OrderListFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, system_id);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public void onResume() {
        super.onResume();
//        if (timer!=null){
//            timer.cancel();
//        }
        if (getArguments() != null) {
            system_id = getArguments().getString(ARG_PARAM1);
            getOrderList();
        }
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        rvShopOrder.setLayoutManager(new NpaLinearLayoutManager(getContext()));
        adapter = new BaseQuickAdapter<OrderBean.ListDTO, CountDownAdapter.MyViewHolder>(R.layout.item_shop_order, dtsu) {
//            @Override
//            public void onViewRecycled(BaseViewHolder holder) {
//                super.onViewRecycled(holder);
//                cancelAllTimers();
//            }

            @Override
            protected void convert(CountDownAdapter.MyViewHolder baseViewHolder,final OrderBean.ListDTO dataBean) {

                baseViewHolder.setText(R.id.tv_shop_name,dataBean.getMerchantName());
                baseViewHolder.setText(R.id.tv_shop_type,getType(dataBean.getOrderState()));
             String  shopcount="0";
                for (int i = 0; i <dataBean.getDetails().size() ; i++) {
                    shopcount = BigDecimalUtils.add(shopcount, dataBean.getDetails().get(i).getCount()+"", 0);

                }
                TextView canncle_tv=baseViewHolder.getView(R.id.canncle_tv);
                TextView lxs_tv=baseViewHolder.getView(R.id.lxs_tv);
                TextView tk_tv= baseViewHolder.getView(R.id.tk_tv);
                TextView tv_shop_name= baseViewHolder.getView(R.id.tv_shop_name);
                TextView tv_zcg= baseViewHolder.getView(R.id.tv_zcg);
                TextView tv_wgj=baseViewHolder.getView(R.id.tv_wgj);

                TextView tv_wc_agine=baseViewHolder.getView(R.id.tv_wc_agine);
              if (dataBean.getTakeCode()!=null){
                  baseViewHolder.setText(R.id.cqm_tv,"取餐号："+dataBean.getTakeCode()+"");
              }
//              联系小哥
                TextView wglx_tv=baseViewHolder.getView(R.id.wglx_tv);
                TextView tv_lx=baseViewHolder.getView(R.id.tv_lx);
                TextView dqlx_tv=baseViewHolder.getView(R.id.dqlx_tv);
                TextView sxlx_tv=baseViewHolder.getView(R.id.sxlx_tv);

                TextView tv_pingjia=baseViewHolder.getView(R.id.tv_pingjia);
                TextView pingjia=baseViewHolder.getView(R.id.tv_button1);
                baseViewHolder.setText(R.id.tv_num_credit,"共"+shopcount+"件商品 合计：￥"+ BigDecimalUtils.add(BigDecimalUtils.div(dataBean.getActualAmountPaid()+"","100",2),BigDecimalUtils.div(dataBean.getFreightProportion()+"","100",2),2)+"(配送费"+BigDecimalUtils.div(dataBean.getFreightProportion()+"","100",2)+"元)");
                //订单状态(0未支付,1支付成功,2配餐中,4配送中,5已存柜,6已接收,7已失效,8已删除(用户不可见))9 无柜存餐待确认 10 已取消 11 失效已取出12支付失败
               if(system_id.equals("10000")){

                    baseViewHolder.setGone(R.id.dfk_layout,true);
                    baseViewHolder.setGone(R.id.dqc_layout,true);
                    baseViewHolder.setGone(R.id.psz_layout,true);
                    baseViewHolder.setGone(R.id.pcz_layout,true);
                    baseViewHolder.setVisible(R.id.dpj_layout,true);
                   baseViewHolder.setGone(R.id.wc_layout,true);

                    baseViewHolder.setGone(R.id.zcg_layout,true);
                    baseViewHolder.setGone(R.id.shd_layout,true);
                    baseViewHolder.setGone(R.id.wgj_layout,true);
                    baseViewHolder.setGone(R.id.agine_layout,true);
                }else {
                   if (dataBean.getOrderState() == 0) {
//状态0 是全部
                       baseViewHolder.setGone(R.id.wc_layout,true);
                       baseViewHolder.setVisible(R.id.dfk_layout, true);
                       baseViewHolder.setGone(R.id.dqc_layout, true);
                       baseViewHolder.setGone(R.id.psz_layout, true);
                       baseViewHolder.setGone(R.id.pcz_layout, true);
                       baseViewHolder.setGone(R.id.dpj_layout, true);
                       baseViewHolder.setGone(R.id.zcg_layout, true);
                       baseViewHolder.setGone(R.id.shd_layout, true);
                       baseViewHolder.setGone(R.id.wgj_layout, true);
                       baseViewHolder.setGone(R.id.agine_layout, true);
                   } else if (dataBean.getOrderState() == 2) {
//状态2 是配餐中

                       baseViewHolder.setGone(R.id.wc_layout,true);
                       baseViewHolder.setGone(R.id.dfk_layout, true);
                       baseViewHolder.setGone(R.id.dqc_layout, true);
                       baseViewHolder.setGone(R.id.psz_layout, true);
                       baseViewHolder.setGone(R.id.shd_layout, true);
                       baseViewHolder.setGone(R.id.wgj_layout, true);
                       baseViewHolder.setGone(R.id.dpj_layout, true);
                       baseViewHolder.setGone(R.id.agine_layout, true);
                       baseViewHolder.setVisible(R.id.pcz_layout, true);
//  返回支付时间状态

                       long timeStamp = System.currentTimeMillis() - tempTime;
                       long time = dataBean.getDifference() - timeStamp;

                       if (baseViewHolder.countDownTimer != null) {
                           baseViewHolder.countDownTimer.cancel();
                       }
                       if (time > 0) {
//                    计时器

                           baseViewHolder.countDownTimer = new CountDownTimer(time, 1000) {

                               @Override
                               public void onTick(long l) {
//                                计时器大于零就显示申请退款按钮
//                                dataBean.setDifference(l);

                                   if (l > 120000) {
                                       baseViewHolder.setVisible(R.id.tick_tv, true);
                                       baseViewHolder.setGone(R.id.tk_tv, true);

                                       baseViewHolder.setEnabled(R.id.tick_tv, false);
//

                                       DecimalFormat dec = new DecimalFormat("##.##");

                                       baseViewHolder.setText(R.id.tick_tv, "0" + (int) Math.floor((l - 120000) / 60000) + ":" + dec.format(((l - 120000) % 60000) / 1000) + "秒后允许退款");
//
                                       baseViewHolder.setBackgroundResource(R.id.tick_tv, R.color.white);
//
                                       baseViewHolder.setTextColor(R.id.tick_tv, getResources().getColor(R.color.color666666));
//


                                   } else if (l < 120000) {
                                       baseViewHolder.setGone(R.id.tick_tv, true);

                                       baseViewHolder.setVisible(R.id.tk_tv, true);
                                       baseViewHolder.setEnabled(R.id.tk_tv, true);
                                       baseViewHolder.setText(R.id.tk_tv, "申请退款");

//
                                       baseViewHolder.setBackgroundResource(R.id.tk_tv, R.drawable.button2);
//

                                       baseViewHolder.setTextColor(R.id.tk_tv, getResources().getColor(R.color.color666666));
//
                                   }


                               }

                               @Override
                               public void onFinish() {
                                   baseViewHolder.setGone(R.id.tick_tv, true);
                                   baseViewHolder.setGone(R.id.tk_tv, true);
//

                               }
                           };
                           baseViewHolder.countDownTimer.start();
                           timerArray.put(dataBean.getOrderId(), baseViewHolder.countDownTimer);
//                        timerArray.clear();
                           Log.e(TAG, "convert: 11111111" + timerArray.size());


////
                       } else if (dataBean.getDifference() == 0) {
                           baseViewHolder.setGone(R.id.tk_tv, true);
                           baseViewHolder.setGone(R.id.tick_tv, true);
                       }


                   } else if (dataBean.getOrderState() == 4) {
                       baseViewHolder.setGone(R.id.dfk_layout, true);
                       baseViewHolder.setGone(R.id.dqc_layout, true);
                       baseViewHolder.setGone(R.id.wc_layout,true);
                       baseViewHolder.setVisible(R.id.psz_layout, true);
                       baseViewHolder.setGone(R.id.pcz_layout, true);
                       baseViewHolder.setGone(R.id.dpj_layout, true);
                       baseViewHolder.setGone(R.id.zcg_layout, true);
                       baseViewHolder.setGone(R.id.shd_layout, true);
                       baseViewHolder.setGone(R.id.wgj_layout, true);
                       baseViewHolder.setGone(R.id.agine_layout, true);
                   } else if (dataBean.getOrderState() == 6) {


                       if (dataBean.getEvaluationState()==0){
                           baseViewHolder.setGone(R.id.dfk_layout,true);
                           baseViewHolder.setVisible(R.id.wc_layout,true);
                           baseViewHolder.setGone(R.id.dqc_layout,true);
                           baseViewHolder.setGone(R.id.psz_layout,true);
                           baseViewHolder.setGone(R.id.pcz_layout,true);
                           baseViewHolder.setGone(R.id.dpj_layout,true);
                           baseViewHolder.setGone(R.id.zcg_layout,true);
                           baseViewHolder.setGone(R.id.shd_layout,true);
                           baseViewHolder.setGone(R.id.wgj_layout,true);
                           baseViewHolder.setGone(R.id.agine_layout,true);
                       }else {
                           baseViewHolder.setGone(R.id.dfk_layout, true);
                           baseViewHolder.setGone(R.id.wc_layout,true);
                           baseViewHolder.setGone(R.id.dqc_layout, true);
                           baseViewHolder.setGone(R.id.psz_layout, true);
                           baseViewHolder.setGone(R.id.pcz_layout, true);
                           baseViewHolder.setGone(R.id.dpj_layout, true);
                           baseViewHolder.setVisible(R.id.zcg_layout, true);
                           baseViewHolder.setGone(R.id.shd_layout, true);
                           baseViewHolder.setGone(R.id.wgj_layout, true);
                           baseViewHolder.setGone(R.id.agine_layout, true);
                       }

                   } else if (dataBean.getOrderState() == 5) {
                       baseViewHolder.setGone(R.id.dfk_layout, true);
                       baseViewHolder.setVisible(R.id.dqc_layout, true);
                       baseViewHolder.setGone(R.id.psz_layout, true);
                       baseViewHolder.setGone(R.id.wc_layout,true);
                      baseViewHolder.setGone(R.id.pcz_layout, true);
                       baseViewHolder.setGone(R.id.dpj_layout, true);
                       baseViewHolder.setGone(R.id.shd_layout, true);
                       baseViewHolder.setGone(R.id.wgj_layout, true);
                       baseViewHolder.setGone(R.id.agine_layout, true);
                   } else if (dataBean.getOrderState() == 9) {
                       baseViewHolder.setGone(R.id.dfk_layout, true);
                       baseViewHolder.setGone(R.id.dqc_layout, true);
                       baseViewHolder.setGone(R.id.wc_layout,true);
                       baseViewHolder.setGone(R.id.psz_layout, true);
                       baseViewHolder.setGone(R.id.pcz_layout, true);
                       baseViewHolder.setGone(R.id.dpj_layout, true);
                       baseViewHolder.setGone(R.id.zcg_layout, true);
                       baseViewHolder.setGone(R.id.shd_layout, true);
                       baseViewHolder.setVisible(R.id.wgj_layout, true);
                       baseViewHolder.setGone(R.id.agine_layout, true);

                   } else if ( dataBean.getOrderState() == 13 || dataBean.getOrderState() == 12) {
                       baseViewHolder.setGone(R.id.dfk_layout, true);
                       baseViewHolder.setGone(R.id.wc_layout,true);
                       baseViewHolder.setGone(R.id.dqc_layout, true);
                       baseViewHolder.setGone(R.id.psz_layout, true);
                       baseViewHolder.setGone(R.id.pcz_layout, true);
                       baseViewHolder.setGone(R.id.dpj_layout, true);
                       baseViewHolder.setGone(R.id.zcg_layout, true);
                       baseViewHolder.setGone(R.id.shd_layout, true);
                       baseViewHolder.setGone(R.id.wgj_layout, true);
                       baseViewHolder.setGone(R.id.agine_layout, true);
                   }else if (dataBean.getOrderState() == 10){
                       baseViewHolder.setGone(R.id.dfk_layout, true);
                       baseViewHolder.setGone(R.id.wc_layout,true);
                       baseViewHolder.setGone(R.id.dqc_layout, true);
                       baseViewHolder.setGone(R.id.psz_layout, true);
                       baseViewHolder.setGone(R.id.pcz_layout, true);
                       baseViewHolder.setGone(R.id.dpj_layout, true);
                       baseViewHolder.setGone(R.id.zcg_layout, true);
                       baseViewHolder.setGone(R.id.shd_layout, true);
                       baseViewHolder.setGone(R.id.wgj_layout, true);
                       baseViewHolder.setVisible(R.id.agine_layout, true);
                       baseViewHolder.setText(R.id.pay_tv_agine,"订单已退款");
                   }else if (dataBean.getOrderState() == 14){
                       baseViewHolder.setGone(R.id.dfk_layout, true);
                       baseViewHolder.setGone(R.id.wc_layout,true);
                       baseViewHolder.setGone(R.id.dqc_layout, true);
                       baseViewHolder.setGone(R.id.psz_layout, true);
                       baseViewHolder.setGone(R.id.pcz_layout, true);
                       baseViewHolder.setGone(R.id.dpj_layout, true);
                       baseViewHolder.setGone(R.id.zcg_layout, true);
                       baseViewHolder.setGone(R.id.shd_layout, true);
                       baseViewHolder.setGone(R.id.wgj_layout, true);
                       baseViewHolder.setVisible(R.id.agine_layout, true);
                       baseViewHolder.setText(R.id.pay_tv_agine,"订单已取消");
                   }else if (dataBean.getOrderState()==11){
                       baseViewHolder.setGone(R.id.dfk_layout, true);
                       baseViewHolder.setGone(R.id.wc_layout,true);
                       baseViewHolder.setGone(R.id.dqc_layout, true);
                       baseViewHolder.setGone(R.id.psz_layout, true);
                       baseViewHolder.setGone(R.id.pcz_layout, true);
                       baseViewHolder.setGone(R.id.dpj_layout, true);
                       baseViewHolder.setVisible(R.id.zcg_layout, true);
                       baseViewHolder.setGone(R.id.shd_layout, true);
                       baseViewHolder.setGone(R.id.wgj_layout, true);
                       baseViewHolder.setGone(R.id.agine_layout, true);

                   }
               }
                //取消订单

//                立即支付
                TextView pay_tv=baseViewHolder.getView(R.id.pay_tv);
                 pay_tv.setOnClickListener(new View.OnClickListener() {
                     @Override
                     public void onClick(View view) {
                      String   actualAmountPaid =  BigDecimalUtils.add(BigDecimalUtils.div(dataBean.getActualAmountPaid()+"","100",2),BigDecimalUtils.div(dataBean.getOrderFreight()+"","100",2),2);
                         startActivity(new Intent(getContext(), PayActivity.class).putExtra("orderId",dataBean.getOrderId()+"").putExtra("orderNumber",dataBean.getOrderNumber()).putExtra("actualAmountPaid",actualAmountPaid));

                         //订单状态(0未支付,1支付成功,2配餐中,4配送中,5已存柜,6已接收,7已失效);
                     }
                 });
                /**
                 * 评价
                 */
                pingjia.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        startActivity(new Intent(getContext(), ShopCommentActivity.class).putExtra("order_id", dataBean.getOrderId()+""));
                    }
                });
                tv_pingjia.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        startActivity(new Intent(getContext(), ShopCommentActivity.class).putExtra("order_id", dataBean.getOrderId()+""));
                    }
                });

//                pay_tv_agine.setOnClickListener(new View.OnClickListener() {
//                    @Override
//                    public void onClick(View view) {
//                        String   actualAmountPaid =  BigDecimalUtils.add(BigDecimalUtils.div(dataBean.getActualAmountPaid()+"","100",2),BigDecimalUtils.div(dataBean.getOrderFreight()+"","100",2),2);
//                        startActivity(new Intent(getContext(), PayActivity.class).putExtra("orderId",dataBean.getOrderId()+"").putExtra("orderNumber",dataBean.getOrderNumber()).putExtra("actualAmountPaid",actualAmountPaid).putExtra("bad","失败"));
//                    }
//                });
                tk_tv.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        // 消息对话框
                        new MessageDialog.Builder(getActivity())
                                // 标题可以不用填写
                                .setTitle("申请退款")
                                // 内容必须要填写
                                .setMessage("是否要申请退款？")
                                // 确定按钮文本
                                .setConfirm(getString(R.string.common_confirm))
                                // 设置 null 表示不显示取消按钮
                                .setCancel(getString(R.string.common_cancel))
                                // 设置点击按钮后不关闭对话框
                                //.setAutoDismiss(false)
                                .setListener(new MessageDialog.OnListener() {

                                    @Override
                                    public void onConfirm(BaseDialog dialog) {
                                        reimburse(dataBean.getOrderId()+"");
                                    }

                                    @Override
                                    public void onCancel(BaseDialog dialog) {
                                        dialog.dismiss();
                                    }
                                })
                                .show();
//                        refundOrder(dataBean.getOrderId()+"");
//                        cancelOrder(dataBean.getOrderId()+"");

                    }
                });
                tv_shop_name.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        startActivity(new Intent(getContext(), BusinessActivity.class).putExtra("id",dataBean.getMerchantId()+""));
                    }
                });

                /**
                 * 联系小哥
                 */





                wglx_tv.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
//
                        lxxg(dataBean.getXgdh());
                    }
                });
                tv_lx.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
//                        联系小哥
                        lxxg(dataBean.getXgdh());
                    }
                });
                dqlx_tv.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
//                        联系商家
                        lxxg(dataBean.getXgdh());
                    }
                });
                sxlx_tv.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
//                        联系商家
                        lxxg(dataBean.getXgdh());
                    }
                });
//                联系商家
                lxs_tv.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
//                        联系商家
                        lxs(dataBean.getSjdh());
                    }
                });

                canncle_tv.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        cancelOrder(dataBean.getOrderNumber());

                    }
                });
                RecyclerView rv_order_goods=baseViewHolder.getView(R.id.rv_order_goods);
                goodsAdp =new BaseQuickAdapter<OrderBean.DetailsDTO, BaseViewHolder>(R.layout.item_order_goods,dataBean.getDetails()) {
                    @Override
                    protected void convert(@NotNull BaseViewHolder baseViewHolder,  OrderBean.DetailsDTO bean) {
                        baseViewHolder.setText(R.id.tv_food_name,bean.getCommodityName());
                        if (bean.getSpecificationName()==null){
                            String condimentsName;
                            if (bean.getCondimentsName()==null){
                                condimentsName="";

                            }else {
                                condimentsName= bean.getCondimentsName();
                            }
                            baseViewHolder.setText(R.id.tv_food_num,"默认"+"  "+condimentsName);
                        }else {
                            String condimentsName;
                            if (bean.getCondimentsName()==null){
                                condimentsName="";

                            }else {
                                condimentsName= bean.getCondimentsName();
                            }
                            baseViewHolder.setText(R.id.tv_food_num,bean.getSpecificationName()+"  "+condimentsName);
                        }

                        baseViewHolder.setText(R.id.tv_chengmoney,"x"+bean.getCount());
                        baseViewHolder.setText(R.id.tv_money,"￥"+BigDecimalUtils.div(bean.getCommodityPrice()+"","100",2));
                        GlideApp.with(getActivity())
                                .load(IntentKey.ORDER_IMAGE+bean.getMainImg())

                                .into((ImageView) baseViewHolder.getView(R.id.goods_iv));

                    }
                };
//                再够一次
                tv_zcg.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                     buyAgain(dataBean.getOrderId()+"",dataBean.getMerchantId()+"");
//
                    }
                });
                //                再够一次
                tv_wc_agine.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        buyAgain(dataBean.getOrderId()+"",dataBean.getMerchantId()+"");

//                        startActivity(new Intent(getContext(), BusinessActivity.class).putExtra("id", dataBean.getMerchantId()+""));
                    }
                });
                tv_wgj.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        confirmReceipt(dataBean.getOrderId()+"");
                    }
                });
                rv_order_goods.setAdapter(goodsAdp);
                ((BaseQuickAdapter<OrderBean.DetailsDTO, BaseViewHolder>) rv_order_goods.getAdapter()).setOnItemClickListener((baseQuickAdapter, view, i) -> {

                    Intent intent = new Intent();
                    if (dataBean.getOrderState()==5){
                        intent.setClass(getContext(), OrderServedDetailsActivty.class);

                    }else {
                        intent.setClass(getContext(), OrderDetailsActivity.class);
                    }
                    intent.putExtra("orderid",dataBean.getOrderId()+"");
                    intent.putExtra("system_id",dataBean.getOrderState()+"");
                    intent.putExtra("difference",dataBean.getDifference()+"");
                    intent.putExtra("orderNumber",dataBean.getOrderNumber()+"");
                    intent.putExtra("merchantId",dataBean.getMerchantId()+"");

                    getActivity().startActivity(intent);

                });
            }

           class MyViewHolder extends BaseViewHolder {

                private CountDownTimer countDownTimer;

                public MyViewHolder(@NotNull View view) {
                    super(view);
                }
            }
        };

        adapter.setOnItemClickListener(new  OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull @NotNull BaseQuickAdapter<?, ?> adapter, @NonNull @NotNull View view, int position) {
                Intent intent = new Intent();
                if (dtsu.get(position).getOrderState()==5){
                    intent.setClass(getContext(), OrderServedDetailsActivty.class);

                }else {
                    intent.setClass(getContext(), OrderDetailsActivity.class);
                }
                intent.putExtra("orderid",dtsu.get(position).getOrderId()+"");
                intent.putExtra("system_id",dtsu.get(position).getOrderState()+"");
                intent.putExtra("difference",dtsu.get(position).getDifference()+"");
                intent.putExtra("orderNumber",dtsu.get(position).getOrderNumber()+"");

                getActivity().startActivity(intent);
            }
        });
        // 创建菜单：
        SwipeMenuCreator mSwipeMenuCreator = new SwipeMenuCreator() {
            @Override
            public void onCreateMenu(SwipeMenu leftMenu, SwipeMenu rightMenu, int position) {

                SwipeMenuItem deleteItem = new SwipeMenuItem(getContext()); // 各种文字和图标属性设置。
//                deleteItem.setImage(R.mipmap.icon_collent_delete);
                deleteItem.setText("删除");
                deleteItem.setTextColor(Color.WHITE);
                deleteItem.setTextSize(14);
                deleteItem.setBackgroundColor(Color.parseColor("#FB4747"));

                deleteItem.setHeight(ViewGroup.LayoutParams.MATCH_PARENT);
                deleteItem.setWidth(300);
                rightMenu.addMenuItem(deleteItem); // 在Item右侧添加一个菜单。
                // 注意：哪边不想要菜单，那么不要添加即可。

            }
        };

//        // 设置监听器。
        rvShopOrder.setSwipeMenuCreator(mSwipeMenuCreator);

        if (rvShopOrder.getItemDecorationCount() == 0) {
            rvShopOrder.addItemDecoration(new MyDecoration(getContext(),
                    MyDecoration.VERTICAL_LIST, R.color.colorf5f5f5, 1));
        }

        OnItemMenuClickListener mItemMenuClickListener = new OnItemMenuClickListener() {
            @Override
            public void onItemClick(SwipeMenuBridge menuBridge, int position) {
                deleteOrder(dtsu.get(position).getOrderId()+"");
                // 任何操作必须先关闭菜单，否则可能出现Item菜单打开状态错乱。
                menuBridge.closeMenu();
                // 左侧还是右侧菜单：
                int direction = menuBridge.getDirection();
                // 菜单在Item中的Position：
                int menuPosition = menuBridge.getPosition();

//
            }
        };
        View emptyview = View.inflate(getContext(), R.layout.empty_emptylayout, null);

        adapter.setEmptyView(emptyview);
        rvShopOrder.setOnItemMenuClickListener(mItemMenuClickListener);
        rvShopOrder.setAdapter(adapter);
//                下拉刷新
        refreshLayout.setOnRefreshListener(new RefreshListenerAdapter() {
            @Override
            public void onRefresh(TwinklingRefreshLayout refreshLayout) {
                super.onRefresh(refreshLayout);
                page = 1;
                dtsu.clear();


//                if (timer != null) {
//                        timer.cancel();
//
//                }

//列表数据
                getOrderList();
            }

            @Override
            public void onLoadMore(TwinklingRefreshLayout refreshLayout) {
                super.onLoadMore(refreshLayout);
                page++;
                getOrderMoreList();
            }
          });
        }



    @Override
    public View onCreateView(@NonNull @NotNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return super.onCreateView(inflater, container, savedInstanceState);
    }

    private void deleteOrder(String orderId) {
        EasyHttp.post(this)
                .api(new DeleteOrderApi().setOrderId(orderId)).request(new HttpCallback<PublicMsgBean>(this) {

            @Override
            public void onSucceed(PublicMsgBean data) {
                if (data.getCode()==0){
                    page = 1;
                    dtsu.clear();
                    getOrderList();
                }
                    toast(data.getList());
            }
              @Override
            public void onFail(Exception e) {
                super.onFail(e);

            }
        });
    }


    private void lxs(String sjdh) {
        ShopPhomeDialog ShopPhomeDialog=new ShopPhomeDialog(getContext(),"联系商家",sjdh);
        ShopPhomeDialog.show();
    }
    private void lxxg(String sjdh) {
        ShopPhomeDialog ShopPhomeDialog=new ShopPhomeDialog(getContext(),"联系小哥",sjdh);
        ShopPhomeDialog.show();
    }
//    再来一单
    private void buyAgain(String orderId,String merchantId) {

        EasyHttp.post(this)
                .api(new BuyAgainApi().setOrderId(orderId)).request(new HttpCallback<BuyAgainBean>(this) {

            @Override
            public void onSucceed(BuyAgainBean data) {
                if (data.getCode()==0) {
//                    if (data.getList().getError()==5){
//                        toast(data.getList().getMsg());
//                    }else if (data.getList().getSuccee()==0){
                        if (data.getList().getSchoolId().equals(SPUtil.get(getContext(),IntentKey.ADDRESSID,""))){
                            startActivity(new Intent(getContext(), BusinessActivity.class).putExtra("id", merchantId));
                        }else {
                            new MessageDialog.Builder(getActivity())
                                    // 标题可以不用填写
                                    .setTitle("是否切换学校")
                                    // 内容必须要填写
                                    .setMessage("需切换到对应校区购买商品")
                                    // 确定按钮文本
                                    .setConfirm(getString(R.string.common_confirm))
                                    // 设置 null 表示不显示取消按钮
                                    .setCancel(getString(R.string.common_cancel))
                                    // 设置点击按钮后不关闭对话框
                                    //.setAutoDismiss(false)
                                    .setListener(new MessageDialog.OnListener() {

                                        @Override
                                        public void onConfirm(BaseDialog dialog) {
                                            EventBusUtils.sendEvent(new Event(EvenConstant.QUWANSHANXIN, data.getList().getSchoolName()));
                                            EventBusUtils.sendEvent(new Event(EvenConstant.QUWANSHANXINID,  data.getList().getSchoolId()));
                                            SPUtil.put(getContext(), IntentKey.ADDRESS,  data.getList().getSchoolName());
                                            SPUtil.put(getContext(), IntentKey.ADDRESSID,  data.getList().getSchoolId());
                                            startActivity(new Intent(getContext(), BusinessActivity.class).putExtra("id", merchantId));
                                        }

                                        @Override
                                        public void onCancel(BaseDialog dialog) {
                                            dialog.dismiss();
                                        }
                                    })
                                    .show();
                        }
                    }


//                }
            }

        });
    }
    private void cancelOrder(String orderid){
        EasyHttp.post(this)
                .api(new CancelOrdereApi().setOrderNum(orderid).setUserId(SPUtil.get(getContext(),IntentKey.USERID,""))).request(new HttpCallback<PublicMsgBean>(this) {

            @Override
            public void onSucceed(PublicMsgBean data) {
                if (data.getCode()==0) {
                    toast(data.getMsg());
                        getOrderList();
                    } else {
                        toast(data.getMsg());

                }
            }

        });
    }
    private void refundOrder(String orderid){
        EasyHttp.post(this)
                .api(new RefundOrderApi().setOrderid(orderid)).request(new HttpCallback<RefundOrderBean>(this) {

            @Override
            public void onSucceed(RefundOrderBean data) {
                if (data.getSuccess()!=null){
                    toast("退款成功");
                    getOrderList();
                }else {
                    toast(data.getErro());
                }
            }
            @Override
            public void onFail(Exception e) {
                super.onFail(e);

            }
        });
    }

    /**
     * 确认收货
     * @param orderID
     */
    private void confirmReceipt(String orderID) {
        EasyHttp.post(this)
                .api(new ConfirmReceiptApi().setOrderId(orderID)).request(new HttpCallback<ConfirmReceiptBean>(this) {

            @Override
            public void onSucceed(ConfirmReceiptBean data) {
//
                if (data.getCode() == 0) {
                    toast("已确认收货");
                    getOrderList();
                }


            }

            @Override
            public void onFail(Exception e) {
                super.onFail(e);

            }
        });
    }
    /**
     *  退款和取消订单
     */
    private void reimburse(String orderid) {
        EasyHttp.post(this)
                .api(new ReimburseApi().setOrderid(orderid)).request(new HttpCallback<ReimburseBean>(this) {

            @Override
            public void onSucceed(ReimburseBean data) {


               if (data.isSuccess()){
                   toast(data.getMsg());
                   getOrderList();
               }else {
                   toast(data.getMsg());
               }
            }
            @Override
            public void onFail(Exception e) {
                super.onFail(e);

            }
        });
    }

    @Override
        protected int getLayoutId () {
            return R.layout.fragment_order_list;
        }

        @Override
        protected void initView () {

        }

        @Override
        protected void initData () {

        }

        public void showMessageFromActivity(String message){
            system_id = message;

            page = 1;
            getOrderList();
        }
    private String type = "";
    private String evaluationState="";
        private void getOrderList(){
            cancelAllTimers();
            timerArray.clear();
             type = "";
             evaluationState="";
            //判断是否为评价
            if(system_id.equals("10000")){
                type ="";
                evaluationState ="0";
            }else{
                type = system_id;
                evaluationState ="";
            }
            new Handler().postDelayed(new Runnable(){
                public void run() {
                    EasyHttp.post(new ApplicationLifecycle()).api(new OrderApi().setUserid(SPUtil.get(getContext(), IntentKey.USERID, ""))
                            .setType(type)
                            .setPageNum(page)
                            .setPageSize(10)
                            .setEvaluationState(evaluationState))
                            .request(new OnHttpListener<OrderBean>() {

                                @Override
                                public void onSucceed(OrderBean data) {
//                                    if (timer != null) {
//                                        timer.cancel();
//
//                                    }
                                    tempTime=System.currentTimeMillis();
                                    dtsu.clear();
                                    dtsu .addAll(data.getList());
                                    adapter.setNewData(dtsu);
                                    adapter.notifyDataSetChanged();
                                    refreshLayout.finishRefreshing();
                                }
                                @Override
                                public void onFail(Exception e) {

                                    refreshLayout.finishRefreshing();
                                }
                            });
                }
            }, 100);
            }
        private void getOrderMoreList(){
            String type = "";
            String evaluationState="";
            //判断是否为评价
            if(system_id.equals("10000")){
                type ="";
                evaluationState ="0";
            }else{
                type = system_id;
                evaluationState ="";
            }
            EasyHttp.post(this).api(new OrderApi().setUserid(SPUtil.get(getContext(), IntentKey.USERID, ""))
                    .setType(type)
                    .setPageNum(page)
                    .setPageSize(10)
                    .setEvaluationState(evaluationState))
                    .request(new HttpCallback<OrderBean>(this) {

                        @Override
                        public void onSucceed(OrderBean data) {

                            dtsu.addAll(data.getList());
                            tempTime=System.currentTimeMillis();
                            if (dtsu.size()>0) {
                                refreshLayout.setEnableLoadmore(true);
                            } else {
                                refreshLayout.setEnableLoadmore(false);
                            }
                            refreshLayout.finishLoadmore();
                        }
                        @Override
                        public void onFail(Exception e) {
                            super.onFail(e);
                            refreshLayout.finishLoadmore();
                        }
                    });
        }
        private String getType(int type){
           String res = "";//订单状态(0未支付,1支付成功,2配餐中,4配送中,5已存柜,6已接收,7已失效,8已删除(用户不可见))9 无柜存餐待确认 10 已取消 11 失效已取出12支付失败
           switch (type){
               case  0:
                   res="待支付";
                   break;
               case  1:
                   res="支付成功";
                   break;
               case  2:
                   res="配餐中";
                   break;
               case  3:
                   res="";
                   break;
               case  4:
                   res="配送中";
                   break;
               case  5:
                   res="已存柜";
                   break;
               case  6:
                   res="已完成";
                   break;
               case  7:
                   res="已失效";
                   break;
               case  8:
                   res="已删除";
                   break;
               case  9:
                   res="无柜存餐待确认";
                   break;
               case  10:
                   res="已退款";
                   break;
               case  11:
                   res="失效已取出";
                   break;
               case  12:
                   res="支付失败";
                   break;
               case  14:
                   res="已取消";
                   break;
           }
            return res;
        }

    @Override
    public void onStop() {
        super.onStop();

//            if (timer != null) {
//                timer.cancel();
//
//            }
        cancelAllTimers();
    }

    @Override
    public void onPause() {
        super.onPause();

        cancelAllTimers();
    }
//    循环停止计时器
    public void cancelAllTimers() {
        Log.e(TAG, "cancelAllTimers: "+ timerArray.size());
        if (timerArray == null) {
            return;
        }
        int size = timerArray.size();
        for (int i = 0; i < size; i++) {
            CountDownTimer cdt = timerArray.get(timerArray.keyAt(i));
            if (cdt != null) {
                cdt.cancel();
            }
        }
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        cancelAllTimers();
    }
}
